import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_enjoy_plus/api/house.dart';
import 'package:flutter_enjoy_plus/utils/Toast.dart';
import 'package:geolocator/geolocator.dart';
import 'package:permission_handler/permission_handler.dart';

class LocationList extends StatefulWidget {
  const LocationList({super.key});

  @override
  State<LocationList> createState() => _LocationListState();
}

class _LocationListState extends State<LocationList> {
  Map<String, dynamic> regeocode = {};
  @override
  void initState() {
    PromptAction.showSuccess("初始化");
    // TODO: implement initState
    super.initState();
    // _getAddressInfo();
    _getPermission();
  }

  void _getPermission() async {
    PermissionStatus status = await Permission.location.request();
    if (status.isGranted) {
      // 权限未授予
      PromptAction.showSuccess('位置权限授予');
      _getAddressInfo();
    } else {
      // 权限未授予
      PromptAction.showFail('位置权限未授予, 请去设置中心开启');
    }
  }

  List aroundList = []; // 附近的地址列表
  _getAddressInfo() async {
    Position res = await Geolocator.getCurrentPosition();
    final latitude = double.parse(res.latitude.toStringAsFixed(6));
    final longitude = double.parse(res.longitude.toStringAsFixed(6));
    PromptAction.showSuccess("当前位置: 精度$longitude, 纬度$latitude");
    final addressInfo = await getAddressInfoAPI(longitude, latitude);
    if (addressInfo?.data['status'] == '1') {
      setState(() {
        regeocode = addressInfo?.data['regeocode'];
      });
      PromptAction.showSuccess(regeocode['formatted_address']);
    }

    final arountInfo = await getAroundAddressInfoAPI(longitude, latitude);
    if (arountInfo.data["infocode"] == "10000") {
      aroundList = arountInfo.data["pois"];
      setState(() {});
    } else {
      PromptAction.showFail(arountInfo.data["info"]);
    }
  }

  List<Widget> getListChild() {
    return aroundList.map((item) {
      return Container(
          color: Colors.white,
          padding: const EdgeInsets.all(10),
          child: Row(
            children: [
              Expanded(child: Text(item["name"])),
              const Row(
                children: [
                  Icon(Icons.arrow_forward_ios, size: 16, color: Colors.black),
                ],
              )
            ],
          ));
    }).toList();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('选择社区'),
      ),
      body: ListView(
        padding: const EdgeInsets.all(10),
        children: [
          Row(
            children: [
              const Text(
                '当前地址',
                style: TextStyle(color: Colors.grey),
              ),
              ElevatedButton(
                  onPressed: () {
                    _getPermission();
                  },
                  child: const Text('获取权限'))
            ],
          ),
          const SizedBox(height: 10),
          Container(
            color: Colors.white,
            padding: const EdgeInsets.all(10),
            child: ElevatedButton(
              onPressed: () {
                _getAddressInfo();
              },
              child: Row(
                children: [
                  Expanded(child: Text(regeocode['formatted_address'] ?? '')),
                  const Row(
                    children: [
                      Icon(Icons.location_searching_outlined,
                          color: Colors.blue),
                      SizedBox(width: 2),
                      Text(
                        '重新定位',
                        style: TextStyle(color: Colors.blue),
                      ),
                    ],
                  )
                ],
              ),
            ),
          ),
          const SizedBox(height: 10),
          const Row(
            children: [
              Text(
                '附近社区',
                style: TextStyle(color: Colors.grey),
              )
            ],
          ),
          const SizedBox(height: 10),
          ListView(
            shrinkWrap: true,
            physics: const NeverScrollableScrollPhysics(),
            children: getListChild(),
          )
        ],
      ),
    );
  }
}
